package com.neu.wms.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description TODO
 * @author DAIJUNQIANG
 * @date 2023/7/4 9:08
 * @version 1.0
 */
@Component
@Data
@ConfigurationProperties(prefix = "token.jwt")
public class JwtUtils {

	//Base64对该令牌进行编码
	private String secret;

	//令牌过期时间 此处单位/毫秒
	private Long expireTime;

	//生成Jwt
	public String generateToken(String username){
		Date nowDate = new Date();

		Date expireDate = new Date(nowDate.getTime() + 1000 * expireTime );

		return Jwts.builder()
				.setHeaderParam("typ", "JWT")
				.setSubject(username) //将来可以得到验证的主体信息
				.setIssuedAt(nowDate)
				.setExpiration(expireDate)// 7天过期
				.signWith(SignatureAlgorithm.HS512, secret)
				.compact();
	}

	//解析Jwt
	public Claims getClaimsByToken(String jwt){
		try{
			return Jwts.parser()
					.setSigningKey(secret) //密钥
					.parseClaimsJws(jwt)
					.getBody();
		}catch (Exception e){
			return null;
		}

	}

	//判断Jwt是否过期
	public boolean isTokenExpired(Claims claims){
		return claims.getExpiration().before(new Date());
	}

}
